package com.erli.exchange.common.validate;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.springframework.web.bind.annotation.RequestBody;

import com.erli.exchange.common.annotation.ModelValid;

public class ModelValidAopHelper {

    public static Object findRequestBodyObject(Method method, Object[] args) {
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if (parameterAnnotations == null || args == null) {
            return null;
        }

        if (parameterAnnotations.length != args.length) {
            return null;
        }

        Object requestBody = null;
        for (int i = 0; i < parameterAnnotations.length; i++) {
            Annotation[] annotations = parameterAnnotations[i];
            for (Annotation annotation : annotations) {
                if (annotation instanceof RequestBody) {
                    requestBody = args[i];
                    break;
                }
            }
            if (requestBody != null) {
                break;
            }
        }
        return requestBody;
    }

    public static ValidateRequestBodyWrapper findValidateRequestBodyWrapper(Method method, Object[] args) {
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if (parameterAnnotations == null || args == null) {
            return null;
        }

        if (parameterAnnotations.length != args.length) {
            return null;
        }

        ValidateRequestBodyWrapper result = null;
        for (int i = 0; i < parameterAnnotations.length; i++) {
            Annotation[] annotations = parameterAnnotations[i];
            for (Annotation annotation : annotations) {
                if (annotation instanceof ModelValid) {
                	result = new ValidateRequestBodyWrapper();
                	result.setGroupClass(((ModelValid) annotation).groupClass());
                	result.setRequestBody(args[i]);
                    break;
                }
            }
            if (result != null) {
                break;
            }
        }
        return result;
    }
}
